package com.lais.record.user.controller;

import com.lais.record.common.auth.UserInfo;
import com.lais.record.common.utils.JwtUtils;
import com.lais.record.common.vo.Result;
import com.lais.record.user.constant.UserConstant;
import com.lais.record.user.constant.UserEnum;
import com.lais.record.user.domain.User;
import com.lais.record.user.exception.UserException;
import com.lais.record.user.properties.JwtProperties;
import com.lais.record.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;

/**
 * @Author: luowen
 * @Description:
 * @Date: Create in 15:15 2019/11/30
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     */
    @PostMapping("login")
    public Result<String> login(@RequestParam(value = "phone",required = false)String phone,@RequestParam(value = "code",required = false)String code) throws Exception {
        log.info("用户登录--start--phone:{}--code:{}",phone,code);
        validParam(phone,code);
        User user = userService.login(phone,code);
        if(UserConstant.UserStatus.CLOCKED.equals(user.getStatus())){
            log.info("用户登录--该用户被锁定--user:{}",user);
            return new Result<>(UserEnum.USER_CLOCKED.getCode(),UserEnum.USER_CLOCKED.getMessage(),false);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setPhone(user.getPhone());
        String token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
        log.info("用户登录成功--end--user:{}",user);
        return new Result<String>(UserEnum.LOGIN_SUCCESS.getCode(),UserEnum.LOGIN_SUCCESS.getMessage(),true,token);
    }

    /**
     * 校验参数
     * @param phone
     * @param code
     */
    private void validParam(String phone, String code) {
        if(StringUtils.isEmpty(phone)){
            log.error("手机号不能为空");
            throw new UserException(UserEnum.PHONE_NOT_EXIST);
        }
        if(StringUtils.isEmpty(code)){
            log.error("验证码不能为空");
            throw new UserException(UserEnum.CODE_NOT_EXIST);
        }
    }
}
